package com.sanyang.pda.ui.putaway;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.sanyang.pda.bean.ByBarcodeBean;
import com.sanyang.pda.bean.GoodsDetailBean;
import com.sanyang.pda.bean.ScanBean;
import com.sanyang.pda.bean.SelectBean;
import com.sanyang.pda.bean.request.PalletSubmit;
import com.sanyang.pda.contract.CheckContract;
import com.sanyang.pda.dialog.ConfrimDialog;
import com.sanyang.pda.dialog.SelectPop;
import com.sanyang.pda.event.EventDate;
import com.sanyang.pda.presenter.CheckPresenter;
import com.sanyang.pda.utils.StringConfig;
import com.sanyang.pda.utils.UserUtils;
import com.sanyang.pda.utils.Utils;
import com.sanyang.pda.view.ScanButView;
import com.sanyang.pda.view.datepicker.CustomDatePicker;
import com.sanyang.pda.view.datepicker.DateFormatUtils;
import com.wangshen.base.app.AppActivityKey;
import com.wangshen.base.ui.mvp.base.ui.BaseMvpActivity;
import com.wangshen.projectbase.R;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = AppActivityKey.PUTAWAYACTIVITY)
public class PutawayActivity extends BaseMvpActivity<CheckPresenter> implements CheckContract.View {
    @BindView(R.id.tv_kuwei)
    TextView tvKuwei;
    @BindView(R.id.tv_tray)
    TextView tvTray;
    @BindView(R.id.tv_clear)
    TextView tvClear;
    @BindView(R.id.tv_goods)
    TextView tvGoods;
    @BindView(R.id.tv_articleName)
    TextView tvArticleName;
    @BindView(R.id.tv_spec)
    TextView tvSpec;
    @BindView(R.id.tv_batchNo)
    EditText tvBatchNo;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_amount)
    TextView tvAmount;
    @BindView(R.id.tv_productTime)
    TextView tvProductTime;
    @BindView(R.id.tv_expiringTime)
    TextView tvExpiringTime;
    @BindView(R.id.tv_checkStatus)
    TextView tvCheckStatus;
    @BindView(R.id.tv_boxSize)
    TextView tvBoxSize;
    @BindView(R.id.comfire)
    Button comfire;
    @BindView(R.id.scan)
    ScanButView scan;
    @BindView(R.id.tv_packUnit)
    TextView tvPackUnit;
    @BindView(R.id.tv_articleUnit)
    TextView tvArticleUnit;
    @BindView(R.id.tv_packNum)
    EditText tvPackNum;
    @BindView(R.id.tv_palletType)
    TextView tvPalletType;
    @BindView(R.id.tv_totalNum)
    TextView tvTotalNum;
    @BindView(R.id.tv_totalFloorNum)
    TextView tvTotalFloorNum;
    @BindView(R.id.et_num)
    EditText etNum;
    @BindView(R.id.iv_pic1)
    ImageView ivPic1;
    @BindView(R.id.iv_pic2)
    ImageView ivPic2;
    @BindView(R.id.iv_pic3)
    ImageView ivPic3;
    @BindView(R.id.tv_storagebinId)
    TextView tvStoragebinId;
    @BindView(R.id.putaway)
    Button putaway;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.title)
    FrameLayout title;
    private String entryNo;
    //ArticleInfoBean articleInfoBean;
    private SelectPop selectPop;
    private List<SelectBean> selectBeans = new ArrayList<>();
    SelectBean states;
    GoodsDetailBean goodsDetailBean;

    @Override
    public CheckPresenter getPresenter() {
        return new CheckPresenter();
    }


    @Override
    public int getView() {
        return R.layout.activity_putaway;
    }

    @Override
    public void initView() {
        selectPop = new SelectPop(mContext, new SelectPop.Onclick() {
            @Override
            public void onClick(SelectBean content) {
                states = content;
                tvCheckStatus.setText(content.getName());
            }
        });
        initDatePicker();
        //presenter.inboundDetail(entryNo,"121","TP22000001");
    }

    @Override
    public void initLinsenterner() {
        scan.setScanCallBack(new ScanButView.ScanCallBack() {
            @Override
            public void callBack(ScanBean scanBean) {
                switch (scanBean.getType()) {
                    case -1://商品
                        /*tvGoods.setText(scanBean.getCode());
                        if (!TextUtils.isEmpty(tvTray.getText().toString())) {
                            presenter.inboundDetail(entryNo, scanBean.getCode(), tvTray.getText().toString());
                        }*/
                        presenter.selectArticleInfoByBarcode(scanBean.getCode(), entryNo);
                        //presenter.selectArticleInfoByBarcode(entryNo, scanBean.getCode());
                        break;
                    case 1://存储库位
                        tvKuwei.setText(scanBean.getCode());
                        break;
                   /* case 2://作业库位
                        tvKuwei.setText(scanBean.getCode());
                        break;*/
                    case 4://托盘
                        tvTray.setText(scanBean.getCode());
                        if (myselectBean != null) {
                            presenter.inboundDetail(entryNo, myselectBean.getId(), tvTray.getText().toString());
                        }
                        break;

                }
            }
        });
        tvPackNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(tvPrice.getText().toString())) {
                    return;
                }
                try {
                    tvAmount.setText(getTotal() + "");
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    showMessage("请输入数字");
                }
            }
        });
        etNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (goodsDetailBean != null) {
                    if (!TextUtils.isEmpty(etNum.getText().toString())) {
                        if (Integer.parseInt(etNum.getText().toString()) > goodsDetailBean.getPackNum()) {
                            etNum.setText(goodsDetailBean.getInNum() % goodsDetailBean.getPackNum() + "");
                        }
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(tvPrice.getText().toString())) {
                    return;
                }
                try {
                    tvAmount.setText(getTotal() + "");
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    showMessage("请输入数字");
                }
            }
        });
        tvPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(tvPrice.getText().toString())) {
                    return;
                }
                try {
                    tvAmount.setText(getTotal() + "");
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    showMessage("请输入数字");
                }
            }
        });
    }

    private String getTotal() {
        if (goodsDetailBean == null) {
            showMessage(getString(R.string.goods) + getString(R.string.not_be_empty));
            return "0.0";
        }
        Double price = 0.0;
        Double packnum = 0.0;
        Double num = 0.0;
        if (!TextUtils.isEmpty(tvPrice.getText().toString())) {
            price = Double.valueOf(tvPrice.getText().toString());
        }
        if (!TextUtils.isEmpty(tvPackNum.getText().toString())) {
            packnum = Double.valueOf(tvPackNum.getText().toString());
        }
        if (!TextUtils.isEmpty(etNum.getText().toString())) {
            num = Double.valueOf(etNum.getText().toString());
        }
        DecimalFormat df = new DecimalFormat("0.00");//精度自己控制保留几位小数点

        return df.format(price * (packnum * goodsDetailBean.getPackNum() + num));
    }

    private float inNum() {
        float packnum = 0;
        float num = 0;
        if (!TextUtils.isEmpty(tvPackNum.getText().toString())) {
            packnum = Float.parseFloat(tvPackNum.getText().toString());
        }
        if (!TextUtils.isEmpty(etNum.getText().toString())) {
            num = Float.parseFloat(etNum.getText().toString());
        }
        return packnum * goodsDetailBean.getPackNum() + num;
    }

    @Override
    public void getData() {
        EventBus.getDefault().register(this);
        Bundle bundle = getIntent().getExtras();
        entryNo = bundle.getString(StringConfig.ENTRYNO);
        states = new SelectBean(getString(R.string.without_quality_inspection), "0");
        selectBeans.add(new SelectBean(getString(R.string.without_quality_inspection), "0"));
        selectBeans.add(new SelectBean(getString(R.string.quality_inspection), "10"));
      /*  selectBeans.add(new SelectBean(getString(R.string.pass), "20"));
        selectBeans.add(new SelectBean(getString(R.string.no_pass), "90"));*/
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void setData(GoodsDetailBean goodsDetailBean) {
        this.goodsDetailBean = goodsDetailBean;
        tvArticleName.setText(goodsDetailBean.getArticleName());
        tvBoxSize.setText(goodsDetailBean.getBoxSize());
        tvSpec.setText(goodsDetailBean.getSpec());
        tvBatchNo.setText(goodsDetailBean.getBatchNo());
        tvExpiringTime.setText(goodsDetailBean.getExpiringTime());
        tvProductTime.setText(goodsDetailBean.getProductTime());
        tvPrice.setText(goodsDetailBean.getPrice());
        tvAmount.setText(goodsDetailBean.getAmount());
        etNum.setText(goodsDetailBean.getInNum() % goodsDetailBean.getPackNum() + "");
        tvPackNum.setText(goodsDetailBean.getInNum() / goodsDetailBean.getPackNum() + "");
        tvArticleUnit.setText(Utils.getArticleUnit(mContext, goodsDetailBean.getArticleUnit()));
        tvPackUnit.setText(Utils.getPackUnit(mContext, goodsDetailBean.getPackUnit()));
        if (!TextUtils.isEmpty(goodsDetailBean.getCheckStatusCn())) {
            states.setId(goodsDetailBean.getCheckStatus());
            states.setName(goodsDetailBean.getCheckStatusCn());
        }
        tvCheckStatus.setText(goodsDetailBean.getCheckStatusCn());
        //tvTray.setText(code);
        tvPalletType.setText(goodsDetailBean.getTbPalletizingMode().getPalletType());
        tvTotalNum.setText(goodsDetailBean.getTbPalletizingMode().getTotalNum() + "");
        tvTotalFloorNum.setText(goodsDetailBean.getTbPalletizingMode().getTotalFloorNum() + "");
        //tvPackUnit.setText(Utils.getPackUnit(mContext, goodsDetailBean.getPackUnit()));
        //tvArticleUnit.setText(Utils.getArticleUnit(mContext, goodsDetailBean.getArticleUnit()));
        // tvPackNum.setText(goodsDetailBean.getPackNum() + "");
        if (goodsDetailBean.getTbPalletizingPicList().size() > 0) {
            if (goodsDetailBean.getTbPalletizingPicList().size() == 1) {
                ivPic1.setVisibility(View.VISIBLE);
                Glide.with(mContext).load(goodsDetailBean.getTbPalletizingPicList().get(0).getPicAddress()).into(ivPic1);
            }
            if (goodsDetailBean.getTbPalletizingPicList().size() == 2) {
                ivPic1.setVisibility(View.VISIBLE);
                ivPic2.setVisibility(View.VISIBLE);
                Glide.with(mContext).load(goodsDetailBean.getTbPalletizingPicList().get(0).getPicAddress()).into(ivPic1);
                Glide.with(mContext).load(goodsDetailBean.getTbPalletizingPicList().get(1).getPicAddress()).into(ivPic2);

            }
            if (goodsDetailBean.getTbPalletizingPicList().size() == 3) {
                ivPic1.setVisibility(View.VISIBLE);
                ivPic2.setVisibility(View.VISIBLE);
                ivPic3.setVisibility(View.VISIBLE);
                Glide.with(mContext).load(goodsDetailBean.getTbPalletizingPicList().get(0).getPicAddress()).into(ivPic1);
                Glide.with(mContext).load(goodsDetailBean.getTbPalletizingPicList().get(1).getPicAddress()).into(ivPic2);
                Glide.with(mContext).load(goodsDetailBean.getTbPalletizingPicList().get(2).getPicAddress()).into(ivPic3);
            }
        }
    }

    @Override
    public void palletSuccess() {
        myselectBean = null;
        goodsDetailBean = null;
        tvTray.setText("");
        tvBatchNo.setText("");
        tvKuwei.setText("");
        tvGoods.setText("");
        tvPalletType.setText("");
        tvTotalNum.setText("");
        tvTotalFloorNum.setText("");
        tvArticleName.setText("");
        tvBoxSize.setText("");
        tvSpec.setText("");
        tvPrice.setText("");
        etNum.setText("");
        tvAmount.setText("");
        tvExpiringTime.setText("");
        tvProductTime.setText("");
        tvPackNum.setText("");
    }

    SelectBean myselectBean;
    List<SelectBean> selectBeanList = new ArrayList<>();

    @Override
    public void setGoodsList(List<ByBarcodeBean> list) {
        if (list.size() == 0) {
            showMessage("未查询到商品信息");
            return;
        }
        if (list.size() == 1) {
            tvGoods.setText(list.get(0).getBarcode());
            tvArticleName.setText(list.get(0).getArticleName());
            myselectBean = new SelectBean(list.get(0).getArticleName(), list.get(0).getArticleId());
            myselectBean.setOther(list.get(0).getBarcode());
            if (!TextUtils.isEmpty(tvTray.getText())) {
                presenter.inboundDetail(entryNo, myselectBean.getId(), tvTray.getText().toString());
            }
        }
        if (list.size() > 1) {
            selectBeanList.clear();
            for (int i = 0; i < list.size(); i++) {
                ByBarcodeBean byBarcodeBean = list.get(i);
                SelectBean selectBean = new SelectBean(byBarcodeBean.getArticleName(), byBarcodeBean.getArticleId());
                selectBean.setOther(byBarcodeBean.getBarcode());
                selectBeanList.add(selectBean);
            }
            SelectPop selectPop = new SelectPop(mContext, new SelectPop.Onclick() {
                @Override
                public void onClick(SelectBean content) {
                    myselectBean = content;
                    tvGoods.setText(content.getOther());
                    tvArticleName.setText(content.getName());
                    if (!TextUtils.isEmpty(tvTray.getText())) {
                        presenter.inboundDetail(entryNo, content.getId(), tvTray.getText().toString());
                    }
                }
            });
            selectPop.show(selectBeanList);
        }
    }


    @OnClick(R.id.tv_clear)
    public void onTvClearClicked() {
        tvTray.setText("");
        tvPalletType.setText("");
        tvTotalNum.setText("");
        tvTotalFloorNum.setText("");
    }

    @OnClick(R.id.tv_productTime)
    public void onTvProductTimeClicked() {
        if (myselectBean != null) {
            Bundle bundle = new Bundle();
            bundle.putString(StringConfig.ENTRYNO, entryNo);
            bundle.putString(StringConfig.ID, myselectBean.getId());
            bundle.putInt(StringConfig.TYPE, 10);
            startIntent(AppActivityKey.CALENDARACTIVITY, bundle);
           /* DateSelectUtils.getInstance().showSelect(this, entryNo, myselectBean.getId(), 10, new DateSelectUtils.OnSelectCallBack() {
                @Override
                public void onSelect(String content) {
                    tvProductTime.setText(content);
                }
            });*/
        }

        // mDatePicker.show(System.currentTimeMillis(), tvProductTime);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventDate(EventDate eventDate) {
        if (eventDate.getType() == 10) {
            tvProductTime.setText(eventDate.getDate());
        } else {
            tvExpiringTime.setText(eventDate.getDate());
        }
    }

    @OnClick(R.id.tv_expiringTime)
    public void onTvExpiringTimeClicked() {
        if (myselectBean != null) {
            Bundle bundle = new Bundle();
            bundle.putString(StringConfig.ENTRYNO, entryNo);
            bundle.putString(StringConfig.ID, myselectBean.getId());
            bundle.putInt(StringConfig.TYPE, 20);
            startIntent(AppActivityKey.CALENDARACTIVITY, bundle);
            /*DateSelectUtils.getInstance().showSelect(this, entryNo, myselectBean.getId(), 20, new DateSelectUtils.OnSelectCallBack() {
                @Override
                public void onSelect(String content) {
                    tvExpiringTime.setText(content);
                }
            });*/
        }
        //mDatePicker.show(System.currentTimeMillis(), tvExpiringTime);
    }

    @OnClick(R.id.tv_checkStatus)
    public void onTvCheckStatusClicked() {
        selectPop.show(selectBeans);
    }

    @OnClick(R.id.comfire)
    public void onComfireClicked() {
        PalletSubmit palletSubmit = new PalletSubmit();
        palletSubmit.setEntryNo(entryNo);
        if (TextUtils.isEmpty(tvTray.getText())) {
            showMessage(getString(R.string.tray) + getString(R.string.not_be_empty));
            return;
        }
        if (TextUtils.isEmpty(tvKuwei.getText())) {
            showMessage(getString(R.string.storage_location) + getString(R.string.not_be_empty));
            return;
        }
        if (TextUtils.isEmpty(tvGoods.getText())) {
            showMessage(getString(R.string.commodity) + getString(R.string.not_be_empty));
            return;
        }
        /*if (TextUtils.isEmpty(tvBatchNo.getText())) {
            showMessage(getString(R.string.batch) + getString(R.string.not_be_empty));
            return;
        }*/
        if (TextUtils.isEmpty(tvPrice.getText())) {
            showMessage(getString(R.string.price) + getString(R.string.not_be_empty));
            return;
        }
        if (TextUtils.isEmpty(etNum.getText())) {
            showMessage(getString(R.string.amount) + getString(R.string.not_be_empty));
            return;
        }
      /*  if (TextUtils.isEmpty(tvProductTime.getText())) {
            showMessage(getString(R.string.date_in_produced) + getString(R.string.not_be_empty));
            return;
        }
        if (TextUtils.isEmpty(tvExpiringTime.getText())) {
            showMessage(getString(R.string.admire_date) + getString(R.string.not_be_empty));
            return;
        }
*/
        palletSubmit.setInNum(inNum() + "");
        palletSubmit.setArticleId(goodsDetailBean.getArticleId());
        palletSubmit.setBatchNo(tvBatchNo.getText().toString());
        palletSubmit.setCheckTtatus(states.getId() + "");
        palletSubmit.setIndexNo(goodsDetailBean.getIndexNo() + "");
        palletSubmit.setExpiringTime(tvExpiringTime.getText().toString());
        palletSubmit.setProductTime(tvProductTime.getText().toString());
        palletSubmit.setCreateBy(UserUtils.getInstance().getUserBean().getUserName());
        palletSubmit.setPallet(tvTray.getText().toString());
        palletSubmit.setPrice(tvPrice.getText().toString());
        palletSubmit.setWorkStoragebinId(tvKuwei.getText().toString());
        palletSubmit.setAmount(tvAmount.getText().toString());
        palletSubmit.setPalletizingMode(goodsDetailBean.getTbPalletizingMode().getPalletizingMode());
        if (inNum() > goodsDetailBean.getRemainingArrivedNum()) {
            ConfrimDialog confrimDialog = new ConfrimDialog(mContext, new ConfrimDialog.Onclick() {
                @Override
                public void onConfirm() {
                    presenter.inventorySubmit(palletSubmit);
                }
            });
            confrimDialog.show(getString(R.string.bcmdsldysy));
        } else {
            presenter.inventorySubmit(palletSubmit);
        }

    }

    private CustomDatePicker mDatePicker;

    private void initDatePicker() {
        long beginTimestamp = DateFormatUtils.str2Long("2000-01-01", false);
        long endTimestamp = DateFormatUtils.str2Long("2500-01-01", false);
        // 通过时间戳初始化日期，毫秒级别
        mDatePicker = new CustomDatePicker(mContext, new CustomDatePicker.Callback() {
            @Override
            public void onTimeSelected(long timestamp, TextView v) {
                v.setText(DateFormatUtils.long2Str(timestamp, false));
            }
        }, beginTimestamp, endTimestamp);
    }


    @OnClick(R.id.putaway)
    public void onViewClicked() {
        PalletSubmit palletSubmit = new PalletSubmit();
        palletSubmit.setEntryNo(entryNo);
        if (TextUtils.isEmpty(tvTray.getText())) {
            showMessage(getString(R.string.tray) + getString(R.string.not_be_empty));
            return;
        }
        if (TextUtils.isEmpty(tvKuwei.getText())) {
            showMessage(getString(R.string.storage_location) + getString(R.string.not_be_empty));
            return;
        }
        if (TextUtils.isEmpty(tvGoods.getText())) {
            showMessage(getString(R.string.commodity) + getString(R.string.not_be_empty));
            return;
        }
        /*if (TextUtils.isEmpty(tvStoragebinId.getText())) {
            showMessage(getString(R.string.storagebinId) + getString(R.string.not_be_empty));
            return;
        }*/
        if (TextUtils.isEmpty(tvPrice.getText())) {
            showMessage(getString(R.string.price) + getString(R.string.not_be_empty));
            return;
        }
        if (TextUtils.isEmpty(etNum.getText())) {
            showMessage(getString(R.string.amount) + getString(R.string.not_be_empty));
            return;
        }
      /*  if (TextUtils.isEmpty(tvProductTime.getText())) {
            showMessage(getString(R.string.date_in_produced) + getString(R.string.not_be_empty));
            return;
        }
        if (TextUtils.isEmpty(tvExpiringTime.getText())) {
            showMessage(getString(R.string.admire_date) + getString(R.string.not_be_empty));
            return;
        }
*/
        palletSubmit.setInNum(inNum() + "");
        palletSubmit.setArticleId(goodsDetailBean.getArticleId());
        palletSubmit.setBatchNo(tvBatchNo.getText().toString());
        palletSubmit.setCheckTtatus(states.getId() + "");
        palletSubmit.setIndexNo(goodsDetailBean.getIndexNo() + "");
        palletSubmit.setExpiringTime(tvExpiringTime.getText().toString());
        palletSubmit.setProductTime(tvProductTime.getText().toString());
        palletSubmit.setCreateBy(UserUtils.getInstance().getUserBean().getUserName());
        palletSubmit.setPallet(tvTray.getText().toString());
        palletSubmit.setPrice(tvPrice.getText().toString());
        //palletSubmit.setWorkStoragebinId(tvKuwei.getText().toString());
        palletSubmit.setAmount(tvAmount.getText().toString());
        palletSubmit.setStoragebinId(tvKuwei.getText().toString());
        palletSubmit.setPalletizingMode(goodsDetailBean.getTbPalletizingMode().getPalletizingMode());
        if (inNum() > goodsDetailBean.getRemainingArrivedNum()) {
            ConfrimDialog confrimDialog = new ConfrimDialog(mContext, new ConfrimDialog.Onclick() {
                @Override
                public void onConfirm() {
                    presenter.palletShelves(palletSubmit);
                }
            });
            confrimDialog.show(getString(R.string.bcmdsldysy));
        } else {
            presenter.palletShelves(palletSubmit);
        }
    }


    @OnClick(R.id.iv_back)
    public void onViewClicked1() {
        finishActivity();
    }
}
